﻿using Microsoft.Extensions.Configuration;
using StackExchange.Redis;

namespace Scm.Orm.Helper
{
    public class RedisHelper
    {
        private static ConnectionMultiplexer? _conn;
        private static RedisConfig? _redisConfig;

        public RedisHelper(IConfigurationSection section)
        {
            _redisConfig = new RedisConfig
            {
                ConnectionString = section["ConnectionString"],
                DBIndex = int.Parse(section["DBIndex"])

            };
            _conn = ConnectionMultiplexer.Connect(_redisConfig.ConnectionString);
        }

        public static bool Save(string Key, string Value, TimeSpan? Exprie = null)
        {
            try
            {
                var _dataBase = _conn?.GetDatabase(_redisConfig?.DBIndex ?? 0);
                if (Exprie == null) _dataBase?.StringSet(Key, Value);
                else _dataBase?.StringSet(Key, Value, Exprie);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public static string? Get(string Key)
        {
            try
            {
                var _dataBase = _conn?.GetDatabase(_redisConfig?.DBIndex ?? 0);
                return _dataBase?.StringGet(Key);
            }
            catch (Exception)
            {
                return null;
            }
        }

    }

    internal class RedisConfig
    {
        public string? ConnectionString { get; set; }
        public int DBIndex { get; set; }
    }
}
